﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBUtility
{
    public static class sqlhelp2
    {
        public static string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        /// <summary>
        /// 公用的方法
        /// </summary>
        /// <param name="con">连接字符串</param>
        /// <param name="cmd"></param>
        /// <param name="cmdText">连接字符串</param>
        /// <param name="comType">SQL命令类型</param>
        /// <param name="paras">参数</param>
        public static void PublicVoid(SqlConnection con, SqlCommand cmd, string strSql, CommandType commandType, SqlParameter[] paras)
        {
            if (con.State != ConnectionState.Open) //判断数据库连接状态
            {
                con.Open();
            }
            else
            {
                con.Close();
            }
            cmd.CommandText = strSql; //SQL语句
            cmd.Connection = con;   //连接字符串
            cmd.CommandType = commandType;  //命令类型
            cmd.CommandTimeout = 0;
            if (paras != null)  //判断命令是否有参数
            {
                foreach (SqlParameter pa in paras) //添加参数到cmd中
                {
                    cmd.Parameters.Add(pa); //把参数一个个的遍历
                }
            }

        }

        /// <summary>
        /// 增，删，改
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="comType">SQL语句的类型</param>
        /// <param name="paras">参数</param>
        /// <returns>Int类型的值</returns>
        public static int ExcuteNonQuery(string strSql, CommandType commandType, SqlParameter[] paras)
        {
            using (SqlConnection con = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                PublicVoid(con, cmd, strSql, commandType, paras);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static int ExecuteNonQuery(string strsql)
        {
            int i = 0;
            using (SqlConnection con = new SqlConnection(connString))
            {
                con.Open();
                SqlCommand sqlcmd = new SqlCommand(strsql, con);
                i = Convert.ToInt32(sqlcmd.ExecuteNonQuery());
                return i;
            }
        }
        /// <summary>
        /// 返回查询结果的第一行第一列
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="comType">SQL语句的类型</param>
        /// <param name="paras">参数</param>
        /// <returns>Object类型的值</returns>
        public static object ExcuteScalar(string cmdText, CommandType comType, SqlParameter[] paras)
        {
            using (SqlConnection con = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                PublicVoid(con, cmd, cmdText, comType, paras);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return obj;
            }
        }
        /// <summary>
        /// 连接模式
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="comType">SQL语句的类型</param>
        /// <param name="paras">参数</param>
        /// <returns>SqlDataReader类型的值</returns>
        public static SqlDataReader ExcuteReader(string cmdText, CommandType comType, SqlParameter[] paras)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand();
            PublicVoid(con, cmd, cmdText, comType, paras);
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            cmd.Parameters.Clear();
            return reader;
        }
        /// <summary>
        /// 断开模式
        /// </summary>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="comType">SQL语句的类型</param>
        /// <param name="paras">参数</param>
        /// <returns>DataTable类型的值</returns>
        public static DataTable ExcuteDataTable(string cmdText, CommandType comType, SqlParameter[] paras)
        {
            using (SqlConnection con = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                PublicVoid(con, cmd, cmdText, comType, paras);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                cmd.Parameters.Clear(); //用完后移除
                return dt;
            }
        }

        /// <summary>
        /// 断开模式
        /// </summary>
        /// <param name="cmdText">语句</param>
        /// <param name="comType">语句的类型</param>
        /// <param name="paras">参数</param>
        /// <returns>DataSet类型的值</returns>
        public static DataSet ExcuteDataSet(string cmdText, CommandType comType, SqlParameter[] paras)
        {
            using (SqlConnection con = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand();
                PublicVoid(con, cmd, cmdText, comType, paras);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                return ds;
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }
        /// <summary>
        /// 构建 OracleCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>OracleCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }
            return command;
        }

        /// <summary>
        /// 执行事务返回有没有成功
        /// </summary>
        /// <param name="sqls">事务中一系列的sql语句</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool ExecuteTran(List<string> sqls)
        {

            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            SqlTransaction st = conn.BeginTransaction();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.Transaction = st;

            try
            {
                //循环便利泛型,一条一条的执行sql语句
                foreach (string sql in sqls)
                {
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
                //循环全部执行成功
                st.Commit();//提交事务
                return true;//事务成功，返回true
            }
            catch
            {
                //有操作出错
                st.Rollback();//回滚事务
                return false;

            }
            finally
            {
                conn.Close();
            }

        }

    }
}
